#include "Egg.h"
#include "ResourceManagers.h"
#include "ChickenDefGame.h"

enum EggStates{INACTIVE,FLYING,XPLODING };

Egg::Egg(ChickenDefGame *_game)
{
	game=_game;
	state=INACTIVE;
	speed = 5.0f;
}
void Egg::Destroy(){
	state=INACTIVE;
}

void Egg::Reset(Vector2f pos,Vector2f _dir){
	dir=_dir;
	//normalizamos por si las moscas
	float norm= sqrtf(dir.x*dir.x+dir.y*dir.y);
	dir.x/=norm;
	dir.y/=norm;

    sf::Image *i=ImageManager::Instance()->GetImage("egg.png");
	m_aniFlying= new AniSprite(*i,64,64);
	m_aniExplode= new AniSprite(*i,64,64);

    m_aniFlying->SetCenter(i->GetWidth()/2,i->GetHeight()/2);


    // rotamos segun la direccion
    if(dir.x>0 && dir.y==0){
        m_aniFlying->Rotate(90);
    }else if(dir.x<0 && dir.y==0){
        m_aniFlying->Rotate(-90);
    }else if(dir.x==0 && dir.y<0){
        m_aniFlying->Rotate(180);
    }else if(dir.x==0 && dir.y>0){
        m_aniFlying->Rotate(180);
    }


	m_aniCurrent= m_aniFlying;
	//m_aniCurrent->Play(0,0);
	m_aniCurrent->SetPosition(pos);
	state=FLYING;
}

bool Egg::IsActive(){
	if (state!=INACTIVE)
		return true;
	return false;
}

void Egg::Update(){

	Vector2f pos;
	Weasel* w;
	switch (state){
	case FLYING:
		pos=m_aniCurrent->GetPosition();

		//ver sino se salio
		if(game->OutOfBounds(pos))
			state=INACTIVE;

		//ver si no chocamos con una comadreja
		w=game->CircleCollidesWithWeasels(m_aniCurrent->GetCenterPosition(), m_aniCurrent->GetFrameCircleRadius());
		if(w!=NULL){
			w->Die();
			state=XPLODING;

			m_aniExplode->SetLoop(false);
			m_aniCurrent=m_aniExplode;
			//m_aniCurrent->Play(0,0);
		}

		//lo movemos
		pos.x+=dir.x*speed;
		pos.y+=dir.y*speed;



		m_aniCurrent->SetPosition(pos);

		m_aniCurrent->Update();
		break;

	case XPLODING:
		m_aniCurrent->Update();
		if(!m_aniCurrent->IsPlaying())
			state=INACTIVE;
		break;

	}


}

void Egg::Draw(RenderWindow* wnd){

	wnd->Draw(*m_aniCurrent);
}

Egg::~Egg(void)
{
}
